/**
 * 
 */
package com.yunyike.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 * @author zhengqiang.shi
 * 2015年11月18日 下午10:01:44
 */
public class HandlerException extends SimpleMappingExceptionResolver{

	private static Logger log = LoggerFactory.getLogger(HandlerException.class);
	
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object arg2,
			Exception ex) {
		
		log.error(ex.getMessage(),ex);
		
		// Expose ModelAndView for chosen error view.  
        String viewName = determineViewName(ex, request); 
        
        if(viewName == null){
        	return null;
        }
        
        // JSP格式返回 
        if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request  
                .getHeader("X-Requested-With")!= null && request  
                .getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {  
            // 如果不是异步请求  
            // Apply HTTP status code for error views, if specified.  
            // Only apply it if we're processing a top-level request.  
            Integer statusCode = determineStatusCode(request, viewName);  
            if (statusCode != null) {  
                applyStatusCodeIfPossible(request, response, statusCode);  
            }
            
    		return getModelAndView(viewName, ex, request);
    		
        } else {// JSON格式返回  
                try {  
                    PrintWriter writer = response.getWriter();
                    writer.write(ex.getMessage());
                    writer.flush();
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                return null;  
  
            }  
	}

}
